package com.roamer.audition.web.security.handler;

import cn.hutool.json.JSONUtil;
import com.roamer.audition.web.security.service.JwtUserService;
import com.roamer.rest.RestResult;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登陆成功处理器
 *
 * @author roamer
 * @version v1.0
 * @date 2020/3/9 16:37
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUserService jwtUserService;

    public LoginSuccessHandler(JwtUserService jwtUserService) {
        this.jwtUserService = jwtUserService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 生成token，并把token加密相关信息缓存
        String token = jwtUserService.generateToken((UserDetails) authentication.getPrincipal());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSONUtil.toJsonStr(RestResult.success(token)));
    }
}
